#!/bin/bash
#
# Quick encryption app. Given a roster of encryption public keys, select them
# and paste some text to encrypt to them.
# 
# See LICENSE for more information on how you can use this program.
#

encrypt() {
    # takes string arguments "cleartext", "recipient"
    # returns string PGP-encrypted data.
    echo "$1" | gpg --armor -r "$2" --encrypt
}

decrypt() {
    # takes string argument "ciphertext", "key"
    # returns string of attempted decrypted data

    # write ciphertext to a temporary file:
    echo "$1" > .quickencrypttempfile
    # --batch option does magic!
    echo "$2" | gpg --passphrase-fd 0 --batch --decrypt .quickencrypttempfile || 
        zenity --error --text "Could not decrypt message"
    rm .quickencrypttempfile
}

# List all public keys available in the system:
KEYS=$(gpg --list-keys | 
    cut -d ">" -f 1 |
    grep "<" |
    sed "s/.*<//g" | 
    tr "\n" "|")

form_data=$(zenity --forms \
    --title "quickencrypt by kzimmermann" \
    --text="Enter some text to encrypt. WARNING: does not sign the data!" \
    --add-entry="Message" \
    --add-combo="Key to encrypt to:" \
    --combo-values="$KEYS" \
    --add-list="Encrypt or decrypt?" \
    --list-values="Encrypt|Decrypt"
)

[[ $? -ne 0 ]] && exit 1

text=$(echo "$form_data" | cut -d "|" -f 1)
recipient=$(echo "$form_data" | tr "\n" "," | cut -d "|" -f 2 | sed "s/\,//g")
action=$(echo "$form_data" | tr "\n" "," | sed "s/\,//g" | cut -d "|" -f 3) || ERROR=2

case $ERROR in
    1 )
        zenity --error \
            --text="Sorry, $recipient's public key is unusable (trust issue?)"
        exit 1
        ;;
    2 )
        zenity --error \
            --text="Please choose an action (encrypt or decrypt) from the menu"
        exit 1
        ;;
    * )
        # Ok, got it!
        ;;
esac

case ${action} in
    "Encrypt" )
        encrypted=$(encrypt "$text" "$recipient")
        echo "$encrypted" | 
            zenity --text-info \
                --width 700 \
                --height 400 \
                --title "Encrypted message to $recipient. Press OK to copy."
        [[ $? -ne 0 ]] && exit
        if [[ -n $(which xsel) ]]
        then
            echo "$encrypted" | xsel -i
        fi
        ;;
    "Decrypt" )
            passwd=$(zenity --password \
                --title="Attempting to decrypt" \
                --text="Enter the password to decrypt this text:"
            )
            echo $(decrypt "$text" "$passwd") | 
                zenity --text-info \
                    --title "Decrypted text output" \
                    --width 500 --height 300 || ERROR=1
        ;;
    * )
        zenity --error \
            --text="Please choose an action (encrypt or decrypt) from the menu"
        exit 1
        ;;
esac
